/**
 * Filename: ThemeActivity.java
 * @author  Firefly
 * @contact postfirefly@163.com
 * @time    2016/4/14 11:41
 */
package com.github.postsanf.yinian.activity;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.ThemeListAdapter;
import com.github.postsanf.yinian.bean.YNTheme;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.ISkinUpdate;
import com.github.postsanf.yinian.entity.YNThemeResponse;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SkinPackageManager;
import com.github.postsanf.yinian.utils.WrapContentGridLayoutManager;
import com.github.postsanf.yinian.utils.YNUrlHelper;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 个性主题
 */
public class ThemeActivity extends BaseActivity implements ISkinUpdate{
    private Toolbar                 mToolbar;
    // 控件
    private RecyclerView            rv_theme_list;
    private ThemeListAdapter        mAdapter;
    private List<YNTheme>           mThemes = new ArrayList<>();
    private DownloadManager         manager ;
    private DownloadCompleteReceiver receiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_theme);
        BaseApplication.getInstance().mActivitys.add(this);
        initView();
    }

    private void  initView() {
        //获取下载服务
        manager =(DownloadManager)getSystemService(DOWNLOAD_SERVICE);
        receiver = new DownloadCompleteReceiver();

        mToolbar = (Toolbar) findViewById(R.id.theme_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);
        rv_theme_list   = (RecyclerView)findViewById(R.id.rv_theme_list);
        WrapContentGridLayoutManager gridLayoutManager = new WrapContentGridLayoutManager(this, 2);
        rv_theme_list.setLayoutManager(gridLayoutManager);
        mAdapter    = new ThemeListAdapter(this, mThemes,manager);
        rv_theme_list.setAdapter(mAdapter);
        getDatas();

        if(!YNUrlHelper.isKitkatUp()){
            showToast("切换主题目前只支持4.4以上系统");
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void getDatas(){
        LinkedHashMap<String,String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_INFO_TYPE, CommonConstants.YNS_DEVICE_ANDROID);
        StringRequest req = new StringRequest(getString(R.string.BASE_URL)+getString(R.string.ynGetTheme))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true){
                    @Override
                    public void onSuccess(String s, Response<String> response){
                        YNThemeResponse resTheme = gson.fromJson(s, YNThemeResponse.class);
                        if (resTheme!=null && ReqUtils.isSuccess(resTheme.getCode())){
                            mThemes.addAll(resTheme.getData());
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                    @Override
                    public void onFailure(HttpException e, Response<String> response){
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    @Override
    public void updateTheme() {
        if(mToolbar!=null){
            try {
                Resources mResource= SkinPackageManager.getInstance(this).mResources;
                if (mResource == null){
                    mToolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_return));
                    mToolbar.setBackgroundColor(getResources().getColor(R.color.yncolor));
                    mToolbar.setTitleTextColor(getResources().getColor(R.color.white));
                    return;
                }
                mToolbar.setNavigationIcon(mResource.getDrawable(mResource.getIdentifier("ic_return", "drawable",CommonConstants.THEME_PACKAGE)));
                mToolbar.setBackgroundColor(mResource.getColor(mResource.getIdentifier("yncolor", "color", CommonConstants.THEME_PACKAGE)));
                mToolbar.setTitleTextColor(mResource.getColor(mResource.getIdentifier("border_color", "color", CommonConstants.THEME_PACKAGE)));
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    //接受下载完成后的intent
    class DownloadCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
                long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
//                Uri url = manager.getUriForDownloadedFile(downId);
                if (mAdapter!=null){
                    mAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(receiver != null)unregisterReceiver(receiver);
        BaseApplication.getInstance().mActivitys.remove(this);
    }

    // 友盟统计
    public void onResume(){
        super.onResume();
        if(SkinPackageManager.getInstance(this).mResources!=null){
            updateTheme();
        }
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause(){
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
